/*
 * @Author: YeMiao 
 * @Date: 2018-02-10 12:48:22 
 * @Last Modified by: YeMiao
 * @Last Modified time: 2018-03-04 13:50:38
 */
import { Component, Input, Output, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { LoginService } from '../login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})

export class LoginComponent implements OnDestroy {
  validateForm: FormGroup;

  // 错误信息
  errorMessage = {
    user: '',
    password: ''
  }

  // 错误信息模板
  formError = {
    user: {
      required: '用户名不能为空'
    },
    password: {
      required: '密码不能为空',
      minlength: '密码不能小于6位数'
    }
  }

  // 提交触发
  _submitForm() {
    let formData = this.validateForm.value;
    this._loginService.login(formData).subscribe(res => {
      if(res['code'] != 1){
        this._notification.blank('登录失败', `时间: ${new Date().toLocaleString()} ${res['err']}`);
      }else{
        let user = res['data'];
        sessionStorage.setItem('user', user.user);
        if(user.name != null) {
          sessionStorage.setItem('name', user.name);
        }
        if(user.email != null) {
          sessionStorage.setItem('email', user.email);
        }
        if(user.phone != null) {
          sessionStorage.setItem('phone', user.phone);
        }
        if(user.sex != null) {
          sessionStorage.setItem('sex', user.sex);
        }
        sessionStorage.setItem('group', user.group);
        sessionStorage.setItem('onTime',new Date().toLocaleTimeString());
        this.router.navigate(['main']);
      }
    });
  }

  constructor(private form: FormBuilder,
    private _notification: NzNotificationService,
    private router: Router,
    private _loginService: LoginService
  ) { }

  ngOnInit() {
    // 表单验证绑定
    this.validateForm = this.form.group({
      user: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required, Validators.minLength(6)] ],
    });
    // 当字段发生改变时触发
    this.validateForm.valueChanges.subscribe(data => this.onChanges(data));
  }

  // 当组件销毁时触发
  ngOnDestroy() {
    this._notification.blank('登陆成功', `时间: ${new Date().toLocaleString()}`);
  }

  // 当字段发生改变时触发
  onChanges(data) {
    for (const field in data) {
      let that = this.validateForm.get(field);
      if(that.dirty && !that.valid){
        if(that.errors != null){
          for(const i in that.errors ){
            this.errorMessage[field] = this.formError[field][i];            
          }
        }
      }else{
        this.errorMessage[field] = '';
      }
    }
  }
}
